package com.estar.platform.caseInfo.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.service.CommonService;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSType;
import org.jeecgframework.web.system.pojo.base.TSTypegroup;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import com.estar.app.business.common.service.AppService;
import com.estar.app.business.common.utils.CompressFile;
import com.estar.platform.caseInfo.entity.TmblCarInfoEntity;
import com.estar.platform.caseInfo.entity.TmblExportInfoEntity;
import com.estar.platform.caseInfo.entity.TmblPicInfoEntity;
import com.estar.platform.caseInfo.entity.TmblSurveyInfoEntity;
import com.estar.platform.caseInfo.utils.FileOperationUtil;
import com.estar.workplace.entity.TmblWorkPlaceEntity;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

@Controller
@RequestMapping("/surveyDown")
public class SurveyDown extends BaseController{
	
	private static final Logger logger = Logger.getLogger(SurveyDown.class);
	@Autowired
     jinYouEval je;
	
	@Autowired
    AppService appService;

	
	@RequestMapping(params = "downLoadCaseInfo")
	public void downLoadCaseInfo(HttpServletRequest request, HttpServletResponse response) {
		InputStream fis = null;
		OutputStream toClient = null;
		String errorNum=null;
			String reportNo = request.getParameter("reportNo"); 	// 案件流水号
			String downType = request.getParameter("downType");		//下载类型	1-分开下载;2-统一下载
			String filePathurl=null;
			String zipFileStr =null;
			try {
				response.setCharacterEncoding("utf-8");
				request.setCharacterEncoding("utf-8");
			//找路径
				TmblPicInfoEntity pic=new TmblPicInfoEntity();
				CriteriaQuery cqp=new CriteriaQuery(TmblPicInfoEntity.class);
				cqp.eq("imageCaseCode", reportNo);
				cqp.isNotNull("imageVhlNO");
				cqp.add();
				List<TmblPicInfoEntity> picList2= appService.getListByCriteriaQuery(cqp, false);
				String url="201606/";
				if(picList2!=null && picList2.size()>0){
					pic=picList2.get(0);
					if(StringUtil.isNotEmpty(pic.getImgPath())){
						url=pic.getImgPath();
						url=url.substring(0, url.indexOf("KCLP"));//==appPicture/201706/
					}
				}
			// 图片存放路径
			String classLocalPath = this.getClass().getClassLoader().getResource("").getPath();
			classLocalPath = classLocalPath.replaceAll("%20", " ");
			classLocalPath = classLocalPath.substring(0, classLocalPath.indexOf("WEB-INF"));
			String filePath = classLocalPath + url+ reportNo;
			filePathurl=classLocalPath;//删除文件时需要
			
			// 查询案件信息
			CriteriaQuery cq = new CriteriaQuery(TmblSurveyInfoEntity.class);
			cq.eq("reportNo", reportNo);
			cq.add();
			List<TmblSurveyInfoEntity> surveyList = appService.getListByCriteriaQuery(cq, false);
			if(surveyList!=null && surveyList.size()>0){
				CriteriaQuery cqw = new CriteriaQuery(TmblWorkPlaceEntity.class);
				cqw.eq("workplace", surveyList.get(0).getWorkSpace());
				cqw.add();
				List<TmblWorkPlaceEntity> worklist=appService.getListByCriteriaQuery(cqw, false);
				if(worklist!=null && worklist.size()>0){
					errorNum=worklist.get(0).getTelephone();
				}
			}

			// 查询车辆信息
			cq = new CriteriaQuery(TmblCarInfoEntity.class);
			cq.eq("reportNo", reportNo);
			cq.add();
			List<TmblCarInfoEntity> carInfoList = appService.getListByCriteriaQuery(cq, false);
			
			
			// 生成压缩包
			SimpleDateFormat sdflocal = new SimpleDateFormat("yyyyMMdd");
			String zipFilPathStr = classLocalPath + "temp" + "/" + reportNo + "/" + new Date().getTime();
			File zipFilPath = new File(zipFilPathStr);
			if (!zipFilPath.exists()) {
				zipFilPath.mkdirs();
			}
			logger.info("生成压缩包路径："+zipFilPathStr);
			
			String cars = "";
			for (int i = 0; i < carInfoList.size(); i++) {
				if ("".equals(cars)) {
					cars = cars + carInfoList.get(i).getCarNo();
					continue;
				}
				cars = cars + "-" + carInfoList.get(i).getCarNo();
			}
			
			String pdfPath = downLoadCasePdf(request, response, appService);
			
			/*精友部分*/
			List<String> jyPdath=new ArrayList<String>();
			if(surveyList!=null && surveyList.size()>0){
				TmblSurveyInfoEntity surveyInfoEntity=surveyList.get(0);
				if (StringUtil.isNotEmpty(surveyInfoEntity.getEvalSur())) {
					if (surveyInfoEntity.getEvalSur().equals("t")) {
						for(TmblCarInfoEntity c:carInfoList){
							if (StringUtil.isNotEmpty(c.getEval())) {
								if(c.getEval().equals("79")){
									jyPdath.add(je.downPdf2(request, response, reportNo, c.getIndexNme()));
								}
							}
							
						}
					}
				}
				
			}
			
			/*end==精友部分*/
			
			//统一下载时执行，分开下载跳过
			if("2".equals(downType)){
				//统一下载时，文件缓存路径
				String unifiedFilPathStr = classLocalPath + "temp" + "/" + reportNo + "/2/" + new Date().getTime();
				File unifiedFilPath = new File(unifiedFilPathStr);
				if(!unifiedFilPath.exists()){
					unifiedFilPath.mkdirs();
				}
				logger.info("生成统一下载路径："+unifiedFilPathStr);
				//查询图片信息表
				CriteriaQuery cq1 = new CriteriaQuery(TmblPicInfoEntity.class);
				cq1.eq("imageCaseCode", reportNo);
				cq1.addOrder("imageTypeClass",SortDirection.asc);
				cq1.add();
				List<TmblPicInfoEntity> picList = appService.getListByCriteriaQuery(cq1, false);
				
				//复制图片
				if(null != picList && picList.size()>0){
					for (int i = 0; i < picList.size(); i++){
						TmblPicInfoEntity picInfo = picList.get(i);
						String oldPath = classLocalPath + picInfo.getImgPath();
						String newPath = unifiedFilPathStr + "/" + i +"_"+picInfo.getImageTypeClass()+"_"+picInfo.getImageTypeSection()+".jpg";
						FileOperationUtil.copyFile(oldPath, newPath);
					}
					FileOperationUtil.copyFile(pdfPath, unifiedFilPathStr+"/"+ reportNo + "+" + sdflocal.format(new Date()) + "(" + cars + ").pdf");
					
					/*精友部分*/
					if (jyPdath.size()>0 && jyPdath!=null) {
						int size=carInfoList.size();
						for(int i=0;i<size;i++){
							TmblCarInfoEntity c=carInfoList.get(i);
							if (StringUtil.isNotEmpty(c.getEval())) {
								if(c.getEval().equals("79")){
									FileOperationUtil.copyFile(jyPdath.get(i), unifiedFilPathStr+"/"+c.getCarNo()+"的定损协议书"+".pdf");
								}
							}
							
						}
						
					}
					/*end==精友部分*/
					
					filePath = unifiedFilPathStr;
					
				}
			}
			  
				
				
				zipFileStr = zipFilPath + "/" + reportNo + "+" + sdflocal.format(new Date())+ ".zip";
				
				logger.info("filePath:"+filePath);
				logger.info("压缩包："+zipFileStr);
				File zipFile = new File(zipFileStr);
				if(zipFile.exists()){
					zipFile.delete();
				}
				CompressFile compressFile =new CompressFile(zipFileStr);
				compressFile.compressExe(filePath);
			
			// 下载压缩包
			String filename = zipFile.getName();
			fis = new BufferedInputStream(new FileInputStream(zipFileStr));
			response.reset();
			response.setContentType("text/html;charset=utf-8");
			request.setCharacterEncoding("UTF-8");
			response.addHeader("Content-Length", "" + zipFile.length());
			toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			response.setHeader("Content-disposition",
					"attachment;filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
				toClient.write(buffer, 0, bytesRead);
			}
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
			fis.close();

			
			
			//更新状态
			for (int i = 0; i < surveyList.size(); i++) {
				TmblSurveyInfoEntity sVo = surveyList.get(i);
				sVo.setCheckFlag("2");
				appService.saveOrUpdate(sVo);
			}

			// 记录下载信息
			TSUser user = ResourceUtil.getSessionUserName(); // 取session用户
			TmblExportInfoEntity exportInfo = new TmblExportInfoEntity();
			exportInfo.setTDptCode(user.getCurrentDepart().getOrgCode());
			exportInfo.setTDptName(user.getCurrentDepart().getDepartname());
			exportInfo.setTExportName(user.getUserName());
			exportInfo.setTExportTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			exportInfo.setTRptNo(reportNo);
			appService.save(exportInfo);
		} catch (Exception e) {
			
			if (toClient != null) {
				try {
					toClient.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			PrintWriter out = null;
			try {
				out = response.getWriter();
				out.print("<div>此案件图片信息不存在，请电话联系<a style='font-weight:bold;left:5px;right:5px;color:red;'>服务点岗亭电话："+errorNum+"，</a>帮忙寻回照片！谢谢！</div>");
				out.flush();
				out.close();
			} catch (Exception e2) {
				logger.error("下载图片系统异常：",e2);
			} finally {
				if (out != null) {
					out.close();
				}
			}
			
			logger.error("下载图片系统异常：",e);
		} finally {
			try {
				if (toClient != null) {
					toClient.close();
				}
				if (fis != null) {
				    fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 删除zip文件
			if(StringUtil.isNotEmpty(filePathurl)){
						String tempFileStr =filePathurl+ "temp" + "/" + reportNo;
						File tempFile = new File(tempFileStr);
						if (tempFile.exists()) {
							FileOperationUtil.deleteAllFilesOfDir(tempFile);
						}
			}
		}
		
	}
	
	
	protected static String replaceStrNULL(String str){
		return str == null || str.isEmpty() ? "" : str;
	}
	/*@RequestMapping(params = "downLoadCasePdf")
	@Transactional*/
	public String downLoadCasePdf(HttpServletRequest request, HttpServletResponse response,CommonService commService) throws Exception {

		OutputStream toClient = null;
		InputStream fis = null;
		String filePath = null;
		PdfWriter writer = null;
		try {
			String reportNo = request.getParameter("reportNo"); // 案件流水号
			

			String hql = "from TmblCarInfoEntity where t_report_no=?";
			List<TmblCarInfoEntity> carInfoList = commService.findHql(hql, reportNo);
			
			String cars = "";
			for (int i = 0; i < carInfoList.size(); i++) {
				if ("".equals(cars)) {
					cars = cars + carInfoList.get(i).getCarNo();
					continue;
				}
				cars = cars + "-" + carInfoList.get(i).getCarNo();
			}
			// PDF存放路径
			SimpleDateFormat sdflocal = new SimpleDateFormat("yyyyMMdd");
			String classLocalPath = this.getClass().getClassLoader().getResource("").getPath();
			classLocalPath = classLocalPath.replaceAll("%20", " ");
			classLocalPath = classLocalPath.substring(0, classLocalPath.indexOf("WEB-INF"));
			
			//加一个日期分类
			TmblPicInfoEntity pic=new TmblPicInfoEntity();
			CriteriaQuery cqp=new CriteriaQuery(TmblPicInfoEntity.class);
			cqp.eq("imageCaseCode", reportNo);
			cqp.isNotNull("imageVhlNO");
			cqp.add();
			List<TmblPicInfoEntity> picList2= appService.getListByCriteriaQuery(cqp, false);
			String url="201606/";
			if(picList2!=null && picList2.size()>0){
				pic=picList2.get(0);
				if(StringUtil.isNotEmpty(pic.getImgPath())){
					url=pic.getImgPath();
					url=url.substring(0, url.indexOf("KCLP"));//==appPicture/201706/
				}
			}
			
			filePath = classLocalPath + url + reportNo + "/" + reportNo + "+" + sdflocal.format(new Date()) + "(" + cars + ").pdf";
			if (new File(filePath).exists()) {
				new File(filePath).delete();
			}
			//filePath = classLocalPath + "caseInfoPdf/" + reportNo + ".pdf";

			// 获取案件信息
			CriteriaQuery cq = new CriteriaQuery(TmblSurveyInfoEntity.class);
			cq.eq("reportNo", reportNo);
			cq.add();
			TmblSurveyInfoEntity surveyInfo = (TmblSurveyInfoEntity) commService.getListByCriteriaQuery(cq, false).get(0);

			// 1.新建document对象
			
			// 第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。
			Document document = new Document(PageSize.A4, 70, 70, 50, 50);
			// 创建字体;
//			BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			// 字体文件存放路径
			String fontPath = classLocalPath + "caseInfoPdf/font/SIMSUN.TTC,1";
			
			//设置字体路径
			BaseFont bf = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
			
			Font titleFont = new Font(bf, 24);// 标题字体;
			Font typeFont = new Font(bf, 16, Font.BOLD);// 类型字体;
			Font textFont = new Font(bf, 12);// 正文字体;
			Font tipsFont = new Font(bf, 10);// 提示字体;
			Font signFont1 = new Font(bf, 14);// 签名字体;
			Font signFont2 = new Font(bf, 14);// 经办人员签名字体;

			// 2.建立一个书写器(Writer)与document对象关联，通过书写器(Writer)可以将文档写入到磁盘中。
			// 创建 PdfWriter 对象 第一个参数是对文档对象的引用，第二个参数是文件的实际名称，在该名称中还会给出其输出路径。
			writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));

			// 3.打开文档
			document.open();

			// 4.向文档中添加内容
			// 通过 com.lowagie.text.Paragraph 来添加文本。
			document.add(new Paragraph("    "+"广东轻微交通事故损害赔偿协议书", titleFont));
			document.add(new Paragraph("\n"));
			document.add(new Paragraph("案件信息", typeFont));
			document.add(new Paragraph("\n"));
			document.add(new Paragraph("案件流水号：" + replaceStrNULL(surveyInfo.getReportNo()), textFont));
			document.add(new Paragraph("事故类型：" + replaceStrNULL(surveyInfo.getAccidentType()), textFont));
			document.add(new Paragraph("出险时间：" + replaceStrNULL(surveyInfo.getDangerTime()), textFont));
			document.add(new Paragraph("出险地点：" + replaceStrNULL(surveyInfo.getDangerPlace()), textFont));
			document.add(new Paragraph("所属交警大队：" + replaceStrNULL(surveyInfo.getTrafficPolice()), textFont));
			document.add(new Paragraph("所属地市：" + replaceStrNULL(surveyInfo.getCity()), textFont));
			document.add(new Paragraph("指引方式：" + replaceStrNULL(surveyInfo.getGuideWay()), textFont));
			
			// 获取事故名字
			TSTypegroup tg = appService.findUniqueByProperty(TSTypegroup.class, "typegroupcode", "accident");
			String accidentName = null;
			for (TSType tc : tg.getTSTypes()) {// 父类中有个获取其所有子类的list方法，遍历这些list
				if (tc.getTypecode().equals(surveyInfo.getAccidentAfter())) {// 判断赋值
					accidentName = tc.getTypename();
				}
			}
			
			document.add(new Paragraph("事故经过：" + accidentName, textFont));
			
			
//			if ("1".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "追尾", textFont));
//			} else if ("2".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "变更车道或越线行驶", textFont));
//			} else if ("3".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "倒车或溜后", textFont));
//			} else if ("4".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "未按照交通信号指示通行", textFont));
//			} else if ("5".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "转弯车未让直行车先行", textFont));
//			} else if ("6".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "逆向行驶", textFont));
//			} else if ("7".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "不按规定超车", textFont));
//			} else if ("8".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "不按规定掉头", textFont));
//			} else if ("9".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "开关车门", textFont));
//			} else if ("10".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "无红绿灯路口未让右侧车辆先行", textFont));
//			} else if ("11".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "右转车辆未让左转车辆先行", textFont));
//			} else if ("12".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "进入环岛车辆未让环岛内车辆先行", textFont));
//			} else if ("13".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "掉头车辆未让正常行驶车辆先行", textFont));
//			} else if ("14".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "未按导向标识行驶", textFont));
//			} else if ("15".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "违反让行标识的", textFont));
//			} else if ("16".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "违反规定在专用车道内行驶", textFont));
//			} else if ("17".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "违反装载规定超长、超宽的", textFont));
//			} else if ("18".equals(surveyInfo.getAccidentAfter())) {
//				document.add(new Paragraph("事故经过：" + "装载的货物在掉落、飘散中导致交通事故的", textFont));
//			}

			document.add(new Paragraph("是否关联案件：" + replaceStrNULL(surveyInfo.getIfCase()), textFont));
			
			String ask=surveyInfo.getAsk();
			document.add(new Paragraph("是否可疑：" + ask, textFont));
			if(StringUtil.isNotEmpty(ask)){
				if(ask.equals("是")){
					document.add(new Paragraph("减损类型：" + surveyInfo.getAskType(), textFont));
					document.add(new Paragraph("减损备注：" + surveyInfo.getAskRrk(), textFont));
				}
			}
			
			
			if (!"".equals(surveyInfo.getRemark()) && surveyInfo.getRemark() != null) {
				document.add(new Paragraph("备注：" + surveyInfo.getRemark(), textFont));
			} else {
				document.add(new Paragraph("备注：无", textFont));
			}

			document.add(new Paragraph("\n"));
			document.add(new Paragraph("车辆信息", typeFont));
			document.add(new Paragraph("\n"));
			
			//判断用哪个模板（乙方）
			//1.无需保险理赔（模板一）
			//2.需保险&&互碰自赔
			//3.需保险&&无责直赔
			int selectTemplate = 0;
			
			//记录责任方
			//1.全责方车牌
			String fullResCarNo = null;
			//2.无责方车牌
			String noResCarNo = null;
			
			//记录领款人信息
			//1.领款人
			String payee = null;
			//2.收款账号
			String  bankNo = null;
			//3.开户银行
			String bankName = null;
			
			//记录全责方保险公司
			String insuranceCompany1 = null;
			String insuranceCompany2 = null;

			
			if (null != carInfoList && carInfoList.size() > 0) {
				for (TmblCarInfoEntity carInfo : carInfoList) {
					document.add(new Paragraph(carInfo.getIndexNme(), textFont)); // 第几车辆
					document.add(new Paragraph("车牌号码：" + replaceStrNULL(carInfo.getCarNo()), textFont));
					document.add(new Paragraph("车辆种类：" + replaceStrNULL(carInfo.getCarType()), textFont));
					document.add(new Paragraph("驾驶员：" + replaceStrNULL(carInfo.getDriverNme()), textFont));
					
					if("是".equals(replaceStrNULL(carInfo.getIfExce()))){
						document.add(new Paragraph("联系电话：" + replaceStrNULL(carInfo.getMoblie()), textFont));// 手机号码
					}else{
						document.add(new Paragraph("联系电话：" + replaceStrNULL(carInfo.getPhone()), textFont));// 手机号码
					}
					

					// 通过组织机构代码找到机构名字
					CriteriaQuery cqCC = new CriteriaQuery(TSDepart.class);
					cqCC.eq("orgCode", carInfo.getCompulsoryCompany());
					cqCC.add();
					TSDepart tSDepart1 = (TSDepart) commService.getListByCriteriaQuery(cqCC, false).get(0);
					document.add(new Paragraph("交强险承保公司：" + replaceStrNULL(tSDepart1.getDepartname()), textFont));
					CriteriaQuery cqBC = new CriteriaQuery(TSDepart.class);
					cqBC.eq("orgCode", carInfo.getBusinessCompany());
					cqBC.add();
					TSDepart tSDepart2 = (TSDepart) commService.getListByCriteriaQuery(cqBC, false).get(0);
					document.add(new Paragraph("商业险承保公司：" + replaceStrNULL(tSDepart2.getDepartname()), textFont));
					

					document.add(new Paragraph("碰撞部位：" + replaceStrNULL(carInfo.getSiteType()), textFont));
					document.add(new Paragraph("事故责任：" + replaceStrNULL(carInfo.getAccidentLiability()), textFont));
					//记录全责方保险公司名称
					if("全责".equals(carInfo.getAccidentLiability())){
						insuranceCompany1 = tSDepart1.getDepartname();
						insuranceCompany2 = tSDepart2.getDepartname();
					}
						
						
						
					// 快赔案件判断
					if ("甲方车辆".equals(carInfo.getIndexNme())) {
						
						//判断甲方责任类型，并记录
						if("全责".equals(carInfo.getAccidentLiability())){
							fullResCarNo = carInfo.getCarNo();
							
						}else{
							noResCarNo = carInfo.getCarNo();
						}
						
						//快赔案件才有被保险人信息
						if ("是".equals(carInfo.getQuickCase())) {
							document.add(new Paragraph("快赔案件：" + replaceStrNULL(carInfo.getQuickCase()), textFont));
							document.add(new Paragraph("被保险人：" + replaceStrNULL(carInfo.getInsuredPerson()), textFont));
							document.add(new Paragraph("开户行：" + replaceStrNULL(carInfo.getBankNme()), textFont));
							document.add(new Paragraph("卡号：" + replaceStrNULL(carInfo.getBankNo()), textFont));
						} else {
							document.add(new Paragraph("快赔案件：" + replaceStrNULL(carInfo.getQuickCase()), textFont));
						}
					}
					
					//// 非单方事故则显示甲方以外的车辆信息
					if (!"单方事故".equals(surveyInfo.getAccidentType())) {
						// 乙方车辆有互碰自赔
						if ("乙方车辆".equals(carInfo.getIndexNme())) {
							
							//通过全责方车牌是否为空判断乙方车辆责任类型，并记录
							if(fullResCarNo==null){
								fullResCarNo = carInfo.getCarNo();
							}else{
								noResCarNo = carInfo.getCarNo();
							}
							
							
							
							if ("需保险理赔".equals(carInfo.getCmethod())) {
								document.add(new Paragraph("赔偿方式：" + replaceStrNULL(carInfo.getCmethod()), textFont));
								if ("是".equals(carInfo.getMtasc())) {
									//需保险理赔，是互碰自赔选择模板二
									selectTemplate = 2;
									document.add(new Paragraph("互碰自赔：" + replaceStrNULL(carInfo.getMtasc()), textFont));
									document.add(new Paragraph("被保险人：" + replaceStrNULL(carInfo.getInsuredPerson()), textFont));
									document.add(new Paragraph("开户行：" + replaceStrNULL(carInfo.getBankNme()), textFont));
									document.add(new Paragraph("卡号：" + replaceStrNULL(carInfo.getBankNo()), textFont));
								} else if ("是".equals(carInfo.getDirectc())) {
									
									//非单方事故，是无责直赔，选择模板三
									selectTemplate = 3;
									document.add(new Paragraph("无责直赔：" + replaceStrNULL(carInfo.getDirectc()), textFont));
									document.add(new Paragraph("领款人：" + replaceStrNULL(carInfo.getPayeePerson()), textFont));
									payee = carInfo.getPayeePerson();
									document.add(new Paragraph("开户行：" + replaceStrNULL(carInfo.getBankNme()), textFont));
									bankName = carInfo.getBankNme();
									document.add(new Paragraph("卡号：" + replaceStrNULL(carInfo.getBankNo()), textFont));
									bankNo = carInfo.getBankNo();
								} else {
									//需保险理赔，不是互碰自赔也不是无责直赔，选择模板二
									selectTemplate = 2;
									
								}
							} else {
								//无需保险理赔选择模板一
								selectTemplate = 1;
								document.add(new Paragraph("赔偿方式：" + replaceStrNULL(carInfo.getCmethod()), textFont));
							}
						} else if(!"甲方车辆".equals(carInfo.getIndexNme()) && !"乙方车辆".equals(carInfo.getIndexNme())){
							if ("需保险理赔".equals(carInfo.getCmethod())) {
								document.add(new Paragraph("赔偿方式：" + replaceStrNULL(carInfo.getCmethod()), textFont));
								if ("是".equals(carInfo.getDirectc())) {
									document.add(new Paragraph("无责直赔：" + replaceStrNULL(carInfo.getDirectc()), textFont));
									document.add(new Paragraph("领款人：" + replaceStrNULL(carInfo.getPayeePerson()), textFont));
									document.add(new Paragraph("开户行：" + replaceStrNULL(carInfo.getBankNme()), textFont));
									document.add(new Paragraph("卡号：" + replaceStrNULL(carInfo.getBankNo()), textFont));
								} else {
									document.add(new Paragraph("无责直赔：" + replaceStrNULL(carInfo.getDirectc()), textFont));
								}
							} else {
								document.add(new Paragraph("赔偿方式：" + replaceStrNULL(carInfo.getCmethod()), textFont));
							}

						}
					}
					document.add(new Paragraph("\n"));
				}
			}
			if (!"单方事故".equals(surveyInfo.getAccidentType())) {
				
				//选择温馨提示模板
				//不需保险理赔的，经双方协商，由 方赔偿 方人民币（大写） 仟佰 拾 元（¥ ），了结此案。
				if(selectTemplate == 1){
					document.add(new Paragraph("\n"));
					document.add(new Paragraph("温馨提示", typeFont));
					document.add(new Paragraph("\n"));
					document.add(new Paragraph("    " + "不需保险理赔的，经双方协商，由_______方赔偿_______方人民币（大写）______仟______佰______拾______元（¥），了结此案。", textFont));
				}
				if(selectTemplate == 2){
					document.add(new Paragraph("\n"));
					document.add(new Paragraph("温馨提示", typeFont));
					document.add(new Paragraph("\n"));
					document.add(new Paragraph("      " + "1)需保险理赔的，事故当事各方保证填报的上述内容均为事实，如有不实，愿负法律责任。", tipsFont));
					document.add(new Paragraph("      " + "  当事人故意填报虚假信息而逃避赔偿责任的，按交通肇事逃逸处理。", tipsFont));
					document.add(new Paragraph("      " + "  当事人故意制造交通事故骗取保险赔款的，将依法承担相应的法律责任。", tipsFont));
					document.add(new Paragraph("      " + "2)如事故车辆没有定损，事故各方当事人修车前，请及时联系保险公司进行定损处理。", tipsFont));
					document.add(new Paragraph("      " + "3)本协议书作为此次交通事故赔偿处理的重要依据，可凭本协议书及其它相关理赔资料向保", tipsFont));
					document.add(new Paragraph("      " + "  险公司办理索赔，如事故各方协商赔偿处理未果，任何一方均可向当地人民法院申请以诉", tipsFont));
					document.add(new Paragraph("      " + "  讼途径处理。", tipsFont));
					document.add(new Paragraph("      " + "4)事故处理过程中有何疑问，可随时电话咨询服务点经办人员。", tipsFont));
				}
				if(selectTemplate == 3){
					document.add(new Paragraph("\n"));
					document.add(new Paragraph("温馨提示", typeFont));
					document.add(new Paragraph("\n"));
					document.add(new Paragraph("      " + "1)需保险理赔的，事故当事各方保证填报的上述内容均为事实，如有不实，愿负法律责任。", tipsFont));
					document.add(new Paragraph("      " + "  当事人故意填报虚假信息而逃避赔偿责任的，按交通肇事逃逸处理。", tipsFont));
					document.add(new Paragraph("      " + "  当事人故意制造交通事故骗取保险赔款的，将依法承担相应的法律责任。", tipsFont));
					document.add(new Paragraph("      " + "2)如事故车辆没有定损，事故各方当事人修车前，请及时联系保险公司进行定损处理。", tipsFont));
					document.add(new Paragraph("      " + "3)本协议书作为此次交通事故赔偿处理的重要依据，可凭本协议书及其它相关理赔资料向保", tipsFont));
					document.add(new Paragraph("      " + "  险公司办理索赔，如事故各方协商赔偿处理未果，任何一方均可向当地人民法院申请以诉", tipsFont));
					document.add(new Paragraph("      " + "  讼途径处理。", tipsFont));
					document.add(new Paragraph("      " + "4)事故处理过程中有何疑问，可随时电话咨询服务点经办人员。", tipsFont));
				}
			}

			document.add(new Paragraph("\n"));
			document.add(new Paragraph("当事人签名", typeFont));
			document.add(new Paragraph("\n"));
			
			//固定输出签名长度12
			String[] blanks = {"", "  ", "    ", "      ", "        ", "          ", "            ", "              ", "               ", "                ", "                 ", "                "};
			// 循环输出事故方联系方式
			for (TmblCarInfoEntity carInfo : carInfoList) {
				if("是".equals(replaceStrNULL(carInfo.getIfExce()))){
					document.add(new Paragraph("   " + replaceStrNULL(carInfo.getIndexNme().substring(0, 2)) + ":" + replaceStrNULL(carInfo.getDriverNme())
					+ blanks[blanks.length-carInfo.getDriverNme().length()] + "   " + "联系电话：" + replaceStrNULL(carInfo.getMoblie()), signFont1));// 手机号码
				}else{
					document.add(new Paragraph("   " + replaceStrNULL(carInfo.getIndexNme().substring(0, 2)) + ":" + replaceStrNULL(carInfo.getDriverNme())
					+ blanks[blanks.length-carInfo.getDriverNme().length()] + "   " + "联系电话：" + replaceStrNULL(carInfo.getPhone()), signFont1));// 手机号码
				}
				document.add(new Paragraph("\n"));
			}
			document.add(new Paragraph("\n"));
			document.add(new Paragraph("   " + "经办人员：" + replaceStrNULL(surveyInfo.getAppUser().getEmpName()) + blanks[8-surveyInfo.getAppUser().getEmpName().length()] + "   " + "联系电话："
						+ replaceStrNULL(surveyInfo.getWorkMobile()), signFont2));
			
			//模板三的补充项，存在全责方才有
			if(selectTemplate == 3 && fullResCarNo != null){
				//添加字体
				//Font signFont = new Font(bf, 14);// 经办人员签名字体;
				document.add(new Paragraph("\n"));
				document.add(new Paragraph("\n"));
				document.add(new Paragraph("    事故当事人经协商，自愿选择“无责直赔”绿色理赔服务，并签署以下授权委托书作为凭证：", textFont));
				document.add(new Paragraph("\n"));
				document.add(new Paragraph("                  保险理赔授权委托书", typeFont));
				document.add(new Paragraph("\n"));
				
				//全责方两家保险公司相同则显示其中一家
				if(insuranceCompany1 == insuranceCompany2){
					document.add(new Paragraph("    " + insuranceCompany1 +"：", textFont));
				}else{
					document.add(new Paragraph("    " + insuranceCompany1 + "、" + insuranceCompany2  + "：", textFont));
				}
				
				
				document.add(new Paragraph("\n"));
				
				//截取出险时间
				String dangerYear = replaceStrNULL(surveyInfo.getDangerTime().substring(0, 4));
				String dangerMonth = replaceStrNULL(surveyInfo.getDangerTime().substring(5, 7));
				String dangerDay = replaceStrNULL(surveyInfo.getDangerTime().substring(8, 10));
				String dangerHour = replaceStrNULL(surveyInfo.getDangerTime().substring(11, 13));
				String dangerMinute = replaceStrNULL(surveyInfo.getDangerTime().substring(14, 16));
				
				//截取创立案件时间
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
				String str=sdf.format(surveyInfo.getCreateTm()); 
				String createYear = replaceStrNULL(str.substring(0, 4));
				String createMonth = replaceStrNULL(str.substring(5, 7));
				String createDay = replaceStrNULL(str.substring(8, 10));
				
				
				
				document.add(new Paragraph("    " + dangerYear + " 年 " + dangerMonth + " 月 " + dangerDay + " 日 " + dangerHour + " 时 " + dangerMinute + " 分，在  " + surveyInfo.dangerPlace 
											+ "  责任方机动车  " + fullResCarNo + "  与无责方机动车  " + noResCarNo 
											+ "  发生碰撞。特向贵司申请，委托贵司直接向第三者支付：□机动车辆损失赔款、□人伤赔款。"
											, textFont));
				document.add(new Paragraph("责任方被保险人签章：_________________    第三者签章：___________________", textFont));
				document.add(new Paragraph("联系电话：______________________         联系电话：____________________", textFont));
				
				document.add(new Paragraph("\n"));
				document.add(new Paragraph("                                      领 款 人：" + replaceStrNULL(payee), textFont));
				document.add(new Paragraph("                                      收款账号：" + replaceStrNULL(bankNo), textFont));
				document.add(new Paragraph("                                      开户银行：" + replaceStrNULL(bankName), textFont));
				document.add(new Paragraph("\n"));
				document.add(new Paragraph("值班人员（见证人）签名："+ replaceStrNULL(surveyInfo.getAppUser().getEmpName())+ "            联系电话：" + replaceStrNULL(surveyInfo.getWorkMobile()), textFont));
				document.add(new Paragraph("服务点盖章：_____________________          " + createYear + " 年 " + createMonth + " 月 " + createDay + " 日 " , textFont));
				
				document.add(new Paragraph("\n"));
				document.add(new Paragraph("    提示说明：第三者包括无责方车主、伤者本人等，第三者是否具有索赔权，由保险公司依法认定。", textFont));
			}
			
			// 5.关闭文档
			document.close();

			// 6.下载pdf
			//设置下载路径
			/*fis = new BufferedInputStream(new FileInputStream(filePath));
			// 设置响应内容类型为PDF类型  
			response.setContentType("application/pdf");
			
			
			// 不在网页中打开，而是直接下载该文件，下载后的文件名为“案件流水号+全部车牌号.pdf”  
			
			//日期格式转换
			//1.出险时间String转换为Date
			SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
			Date date =  formatter.parse(surveyInfo.getDangerTime());
			//2.转换为指定的Date格式
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String dangerTime = sdf.format(date);
			
			
			//循环得到车牌号字符串
			String carNoList = null;
			for (TmblCarInfoEntity carInfo : carInfoList) {
				carNoList += "-" + carInfo.getCarNo();
			}
			String carNos = carNoList.substring(5);
			
			//文件名以案件流水号+出险时间+车牌号命名
			String ouputFileName = reportNo + "+" + dangerTime +"(" + carNos + ")";
			response.setHeader("Content-disposition", "attachment;filename=" 
					+ new String( ouputFileName.getBytes( "gb2312" ), "ISO8859-1" ) + ".pdf");
			toClient = new BufferedOutputStream(response.getOutputStream());

			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
				toClient.write(buffer, 0, bytesRead);
			}
			toClient.write(buffer);

			toClient.flush();
			toClient.close();
			fis.close();
			
			
			// 删除生成的PDF文件
			FileOperationUtil.deleteFile(filePath);*/
			
			
		} catch (Exception e) {
			logger.error("打印pdf系统异常：",e);
			throw e;
		} finally {
			if (toClient != null) {
				toClient.close();
			}
			if (fis != null) {
				fis.close();
			}
			if(writer!=null){
				writer.close();
			}
		}
		return filePath;
	}
}
